<?php
namespace app\applet\controller;

use app\common\model\TokenCheck;
use app\manage\model\Action;
use app\manage\model\AdminUser;
use app\manage\model\OperationLog;
use app\manage\model\RoleAction;
use think\Controller;
use think\Db;
use think\Request;
use think\Validate;

class AdminLogin extends Controller {
    public function __construct(Request $request = null)
    {
//        parent::__construct($request);

        $this->token_check = new TokenCheck();
    }

    public function login()
    {
        $input = input();
        $validate = new Validate([
            ['admin_tel', 'require|max:11|/^1[3-8]{1}[0-9]{9}$/', '手机号码不能为空|手机号码不能超过11个字符|手机号码格式不正确'],
            ['admin_pwd', 'require|min:6|max:256', '密码不能为空|密码长度不能小于6位|密码长度不能大于12位']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        //密码前端加密后传过来，防止中途截获，密码加密规则 密码拼接api_sign_key后md5
        $where['admin_tel'] = trim( $input['admin_tel'] );
        $res = Db::name( 'admin_user' )
            ->field( "admin_id, start_login_time, role_id, admin_sign,admin_status,admin_pwd,name,admin_tel,job_number,department_name, open_id, wechat_open_id")
            ->where( $where )
            ->find();
        if( $res){
            // 若是首次登陆，则提醒用户设置密码
//            if ($res['start_login_time'] == 0) {
//                returnJson(205,"首次登陆，请设置密码")->send();die;
//            }

            //验证用户是否启用
            if ($res['admin_status'] !== 1) {
                returnJson(-2007,"账户被禁用")->send();die;
            }

            // 验证密码
            $model = new AdminUser();
            $key = $model->getKey($res['admin_id']);
            if (md5($input['admin_pwd'] . $key['key']) !== $res['admin_pwd']) {
                returnJson(-1008,"账号或者密码错误")->send();die;
            }

            $ip = get_real_ip();
            $time = time();
            //生成token，以后每次接口请求，都带token，否则未登录，token参与sign签名
            //根据业务。记录登录需要的信息或者日志，比如登录次数，登录时间，登录ip等
            $data = array(
                'create_time' => $time,
                'log_user' => $res['admin_id'],
                'operation' => 1,
                'extra' => $ip
            );
            $resAdd = OperationLog::create($data);
            if (!$resAdd) {
                returnJson(-2001,"服务器错误")->send();die;
            }

            // 判断是否是第一次登陆，若是第一次登陆，则更新第一次登陆时间
            if ($res['start_login_time'] == 0) {
                $updateData['start_login_time'] = $time;
            }

            // 更新登陆次数、最后一次登陆ip，最后一次登陆时间
            $updateData['last__ip'] = $ip;
            $updateData['last_time'] = $time;
            $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->update($updateData);
            if ($resUpdate) {
                $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->setInc('login_num', 1);
                if ($resUpdate) {
                    // 返回页面权限，筛选菜单
                    $data_per = array();
                    if (intval($res['admin_id']) == 1 || intval($res['admin_sign']) == 1) {
                        $model = new Action();
                        $permission = $model->m_list_y();
                        foreach ($permission as $value) {
//                            if ($value['id'] >= config('permission')['min'] && $value['id'] <= config('permission')['max'])
                            if (true)
                                array_push($data_per, $value['id']);
                        }
                    } else {
                        $model = new RoleAction();
                        $detail = $model->detail_q($res['role_id']);
                        if (!empty($detail['action_id'])) {// 小程序只需要最后一级权限
                            $data_per = explode(',', $detail['action_id']);
                        }
                    }

                    /**
                     * 获取小程序openid
                     */
                    if (empty($res['open_id'])) {
                        $params['appid'] = config('applet')['staff']['appid'];
                        $params['secret'] = config('applet')['staff']['secret'];
                        $params['js_code'] = define_str_replace($input['code']);
                        $params['grant_type'] = 'authorization_code';
                        $http_key = httpCurl('https://api.weixin.qq.com/sns/jscode2session', $params, 'GET');
                        $session_key = json_decode($http_key, true);
                        $model = new AdminUser();
                        $model->m_update($res['admin_id'], ['open_id'=>$session_key['openid']]);
                    }


                    /**
                     * 获取公众号openid
                     */
//                    if (empty($res['wechat_open_id'])) {
//                        $subscription_code = $input['wxcode'];
//                        $WeChat = new  \Template\Wechat();
//                        $WeChat->getAdminInfo($res['admin_tel'], $subscription_code);
//                    }

                    $add_extra = [
                        'name' => $res['name'],
                        'admin_tel' => $res['admin_tel'],
                        'job_number' => $res['job_number'],
                        'department_name' => $res['department_name']
                    ];

                    returnJson(200,'操作成功', $this->token_check->createToken($res['admin_id']), $data_per, $add_extra)->send();die;
                } else {
                    returnJson(-2001,"服务器错误")->send();die;
                }
            } else {
                returnJson(-2001,"服务器错误")->send();die;
            }

        }else{
            returnJson(-1008,"账号或者密码错误")->send();die;
        }
    }

    /**
     * 修改名称
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editName() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['name', 'require', '名称不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $name = $input['name'];

        $model = new AdminUser();
        $data = ['name'=>$name];
        $model->m_update($id, $data);


        returnJson(200,"成功")->send();die;
    }

    /**
     * 修改头像
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editIcon() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['icon', 'require', '头像不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $icon = $input['icon'];

        $model = new AdminUser();
        $data = ['icon'=>$icon];
        $model->m_update($id, $data);


        returnJson(200,"成功")->send();die;
    }

    /**
     * 获取员工信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserInfo() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];

        $model = new AdminUser();
        $data = $model->detail($id);


        returnJson(200,"成功", $data)->send();die;
    }

}